package ee.fj.utils;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class ImageResizer {
	public static Dimension getScalingDimension(int fromWidth, int fromHeight, int toWidth, int toHeight) {
		double ratioW = (double)toWidth / (double)fromWidth;
		double ratioH = (double)toHeight / (double)fromHeight;
		double ratio = ratioW < ratioH ? ratioW : ratioH;
		toWidth = (int)(fromWidth * ratio);
		toHeight = (int)(fromHeight * ratio);
		return new Dimension(toWidth, toHeight);
	}

	public static Image resize(Image image, Dimension d) {
		return resize(image, d.width, d.height);
	}

	public static Image resize(Image image, int width, int height) {
		BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		return resizedImage;
	}

	public static Image scale(Image image, Dimension d) {
		return scale(image, d.width, d.height);
	}

	public static Image scale(Image image, int width, int height) {
		return resize(image, getScalingDimension(image.getWidth(null), image.getHeight(null), width, height));
	}
}
